from sqlalchemy.orm import Session
from typing import Optional, Dict, Any
from app.models.models import Account
from app.database.repository.account_repository import AccountRepository
from app.database.repository.user_repository import UserRepository
from app.schemas.account import AccountRecharge
from app.exception.code_exception import CodeException
from app.core.pagination import Pageable, Page
from app.services.user_service import UserService

class AccountService:
    """
    账户服务类，处理账户相关的业务逻辑
    """
    
    def __init__(self, db: Session):
        self.repo = AccountRepository(db)
        self.user_service = UserService(db)
    
    def get_account_by_user_id(self, user_id: int) -> Optional[Account]:
        """
        根据用户ID获取账户
        """
        # 查找账户
        account = self.repo.find_one(Account.user_id == user_id)
        return account
    
    def recharge(self, account_id: int, recharge_data: AccountRecharge) -> Account:
        """
        账户充值
        """
        # 查找账户
        account = self.repo.find_one(account_id)
        if not account:
            raise CodeException.resource_not_found("账户不存在")
        
        # 验证充值金额
        if recharge_data.amount <= 0:
            raise CodeException.sys_error("充值金额必须大于0")
        
        # 执行充值
        updated_account = self.repo.update_balance(account_id, recharge_data.amount)
        
        return updated_account
    
    def check_balance(self, account_id: int, required_amount: float) -> bool:
        """
        检查账户余额是否足够
        """
        account = self.repo.find_one(account_id)
        if not account:
            return False
        
        return account.balance >= required_amount